#include "trackplayer.h"
#include "winsock.h"
#include <QDebug>
#include <Qtimeline>
#include <Qtimer>
trackplayer::trackplayer(QObject *parent) :
    QObject(parent)
{
}
trackplayer::trackplayer(track a,HMIDIOUT hdl)
{
    trackNotes = a.trknotes;
    handle = hdl;
    cNote =0;
}
void trackplayer::playtrk()
{


      QTimer::singleShot(0,this,SLOT(playNote()));
}
void trackplayer::playNote()
{

    //qDebug("cnote %ld\n",n.message);
    midiOutShortMsg(handle,trackNotes[cNote].message);
    cNote++;

    if(cNote<trackNotes.size())
        QTimer::singleShot(trackNotes[cNote].deltaTime*2,this,SLOT(playNote()));

}
void trackplayer::setup(track a, HMIDIOUT hdl)
{
    trackNotes = a.trknotes;
    handle = hdl;
    cNote =0;

}
void trackplayer::sleepplay()
{
    for(int i=0;i<trackNotes.size();i++)
    {
        usleep(trackNotes[i].deltaTime*1.6*1000);
        midiOutShortMsg(handle,trackNotes[i].message);
    }
}
int trackplayer::usleep(long usec)
{
    struct timeval tv;
    fd_set dummy;
    SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    FD_ZERO(&dummy);
    FD_SET(s, &dummy);
    tv.tv_sec = usec/1000000L;
    tv.tv_usec = usec%1000000L;
    return select(0, 0, 0, &dummy, &tv);
}

void trackplayer::timerplay()
{
    lastevent=0;
    timeline= new QTimeLine(100000);
    //timeline->setDuration(3000);
    timeline->setFrameRange(0, 100);
    //timeline->setUpdateInterval(2);
    connect(timeline,SIGNAL(frameChanged(int)),this,SLOT(playwithtimer(int)));
    timeline->start();
    Sleep(1);
    qDebug()<<timeline->currentTime();

     //QTimer::singleShot(0,this,SLOT(playwithtimer()));
}
void trackplayer::playwithtimer(int t)
{
    qDebug()<<timeline->currentTime();

    currentime =timeline->currentTime();

    if(trackNotes[cNote].deltaTime<=currentime-lastevent)
    {
        midiOutShortMsg(handle,trackNotes[cNote].message);
        lastevent+=trackNotes[cNote].deltaTime;
        cNote++;
    }
   // QTimer::singleShot(1000,this,SLOT(playwithtimer()));

}
